package com.wuwangfu.process;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @Author: jcshen
 * @Date: 2023-03-08
 * @PackageName: com.wuwangfu.process
 * @ClassName: SideOutputTag
 * @Description: 测输出流
 * @Version: 1.0.0
 *
 * https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/dev/datastream/side_output/
 *
 *
 */
public class SideOutputTag {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> line = env.socketTextStream("localhost", 8888);

        //侧输出流
        OutputTag<String> odd = new OutputTag<String>("odd") {
        };
        OutputTag<String> even = new OutputTag<String>("even") {
        };
        OutputTag<String> nan = new OutputTag<String>("nan") {
        };


        SingleOutputStreamOperator<String> mainStream = line.process(new ProcessFunction<String, String>() {
            @Override
            public void processElement(String value, Context context, Collector<String> out) throws Exception {
                try {
                    int i = Integer.parseInt(value);
                    if (i % 2 == 0) {
                        //偶数
                        context.output(even, value);
                    } else {
                        //奇数
                        context.output(odd, value);
                    }
                } catch (Exception e) {
                    context.output(nan, value);
                }
                //在主流中输出全部的数据
                out.collect(value);
            }
        });

        mainStream.getSideOutput(odd).print("odd：");
        mainStream.getSideOutput(even).print("even：");
        mainStream.getSideOutput(nan).print("nan：");
        mainStream.print("main：");

        env.execute();
    }
}
